﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace Tools.CryptoService
{
    public class DSA
    {



        public static byte[] SignHash(byte[] HashToSign, DSAParameters DSAKeyInfo, string HashAlg)
        {
            try
            {
                //SHA1 _sha1 = new SHA1CryptoServiceProvider();


                //Encoding _encoding = Encoding.Default;
                //byte[] bb = _encoding.GetBytes(strContent);
                //byte[] bMessageDigest = _sha1.ComputeHash(bb);

                //Create a new instance of DSACryptoServiceProvider.
                DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();

                //Import the key information.   
                DSA.ImportParameters(DSAKeyInfo);

                //Create an DSASignatureFormatter object and pass it the 
                //DSACryptoServiceProvider to transfer the private key.
                DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(DSA);

                //Set the hash algorithm to the passed value.
                DSAFormatter.SetHashAlgorithm(HashAlg);

                //Create a signature for HashValue and return it.
                return DSAFormatter.CreateSignature(HashToSign);
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);

                return null;
            }

        }

        public static bool VerifyHash(byte[] HashValue, byte[] SignedHashValue, DSAParameters DSAKeyInfo, string HashAlg)
        {
            try
            {
                //Create a new instance of DSACryptoServiceProvider.
                DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();

                //Import the key information. 
                DSA.ImportParameters(DSAKeyInfo);

                //Create an DSASignatureDeformatter object and pass it the 
                //DSACryptoServiceProvider to transfer the private key.
                DSASignatureDeformatter DSADeformatter = new DSASignatureDeformatter(DSA);

                //Set the hash algorithm to the passed value.
                DSADeformatter.SetHashAlgorithm(HashAlg);

                //Verify signature and return the result. 
                return DSADeformatter.VerifySignature(HashValue, SignedHashValue);
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);

                return false;
            }

        }
    }
}
